package com.nnxy.controller;
import com.nnxy.service.EmpService;
import com.nnxy.pojo.Emp;
import com.nnxy.pojo.PageResult;
import com.nnxy.pojo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;


@RestController
@RequestMapping("/emps")
public class EmpController {

    @Autowired
    private EmpService empService;
    /**
     * @RequestParam(defaultValue = "1") 设置参数默认值1，前端没有传递这个数据就会采用默认值
     * @DateTimeFormat(pattern = "yyyy-MM-dd") 针对前端传递日期格式化后赋值给LocalDate，不格式化就报错
     */
    @GetMapping
    public Result page(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10")  Integer pageSize,
            String name,
            Integer gender,
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
            @DateTimeFormat(pattern = "yyyy-MM-dd")  LocalDate end
    ){
        //1.调用业务层进行分页查询数据返回PageResult
        PageResult<Emp> pageResult = empService.findByPage(page, pageSize, name, gender, begin, end);

        //2.封装Result返回
        return new Result(1,"success",pageResult);
    }

    @PostMapping
    public Result add(@RequestBody Emp emp){
        try {
            empService.add(emp);
            return new Result(1,"success",null);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(0,"添加员工失败.",null);
        }
    }

    @DeleteMapping
    public Result batchDelete(@RequestParam("ids") List<Integer> ids){
        try {
            empService.batchDelete(ids);
            return new Result(1,"success",null);
        } catch (Exception e) {
            return new Result(0,"批量删除员工失败"+e.getMessage(),null);
        }
    }

    @GetMapping("/{id}")
    public Result findById(@PathVariable Integer id){
        Emp emp=empService.findById(id);
        return new Result(1,"success",emp);
    }

    @PutMapping
    public Result update(@RequestBody Emp emp){
        try{
            empService.modify(emp);
            return new Result(1, "修改成功", null);
        }catch (Exception e) {
            return new Result(0,"修改失败",null);
        }
    }
}